﻿/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/
using Microsoft.VisualBasic;
using MetaBuilders.WebControls;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Enums;
using Votations.NSurvey.Web;


namespace Votations.NSurvey.WebAdmin
{
    /// <summary>
    /// Edit form for a single question
    /// </summary>
    public partial class EditSingleQuestion : PageBase
    {

        public override string ActionCode
        {
            get
            {
                return "100";//新建调查报告
            }
        }

        protected bool MultipleSelection
        {
            get { return (bool)ViewState["MultipleSelection"]; }
            set { ViewState["MultipleSelection"] = value; }
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {
            SetupSecurity();
            LocalizePage();

            ValidateRequestQuestionId();
            MessageLabel.Visible = false;

            ScriptManager.GetCurrent(this).RegisterPostBackControl(ExportXMLButton);
            if (!Page.IsPostBack)
            {
         
                FillDefaultFields();
                BindQuestionOptions();
            }
        }

        private void SetupSecurity()
        {
            CheckRight(NSurveyRights.AccessFormBuilder, true);
        }

        private void LocalizePage()
        {
            EditQuestionTitle.Text = GetPageResource("EditQuestionTitle");
            SelectionModeLabel.Text = GetPageResource("SelectionModeLabel");
            DisplayModeLabel.Text = GetPageResource("DisplayModeLabel");
            ColumnNumberLabel.Text = GetPageResource("ColumnNumberLabel");
            RandomizeAnswersLabel.Text = GetPageResource("RandomizeAnswersLabel");
            AnswerRatingLabel.Text = GetPageResource("AnswerRatingLabel");
            MinSelectionLabel.Text = GetPageResource("MinSelectionLabel");
            MaxSelectionAllowed.Text = GetPageResource("MaxSelectionAllowed");
            UpdateQuestionButton.Text = GetPageResource("UpdateQuestionButton");
            EditAnswersButton.Text = GetPageResource("EditAnswersButton");
            QuestionPipeAliasLabel.Text = GetPageResource("QuestionPipeAliasLabel");
            ExportXMLButton.Text = GetPageResource("ExportXMLButton");
            if (!Page.IsPostBack)
            {
                ColumnDropdownlist.Items.Insert(0, new ListItem(GetPageResource("NoSelectionRequiredOption"), "0"));
                MinSelectionDropDownList.Items.Insert(0, new ListItem(GetPageResource("NoSelectionRequiredOption"), "0"));
                MaxAllowedDropDownList.Items.Insert(0, new ListItem(GetPageResource("UnlimitedSelectionOption"), "0"));
            }
        }


        private void ValidateRequestQuestionId()
        {
            _questionId =
                Information.IsNumeric(Request["QuestionId"]) ? int.Parse(Request["QuestionId"]) : -1;

            if (_questionId == -1)
            {
                throw new FormatException("Invalid question id!");
            }
        }

        /// <summary>
        /// Get the current DB stats and fill 
        /// the label with them
        /// </summary>
        private void FillDefaultFields()
        {
            DisplayModeDropDownList.DataSource = new Questions().GetQuestionLayoutModes();
            DisplayModeDropDownList.DataMember = "LayoutModes";
            DisplayModeDropDownList.DataTextField = "Description";
            DisplayModeDropDownList.DataValueField = "LayoutModeID";
            DisplayModeDropDownList.DataBind();
            TranslateListControl(DisplayModeDropDownList);

            SelectionModeDropDownList.DataSource = new Questions().GetSelectableQuestionSelectionModes();
            SelectionModeDropDownList.DataMember = "QuestionSelectionModes";
            SelectionModeDropDownList.DataTextField = "Description";
            SelectionModeDropDownList.DataValueField = "QuestionSelectionModeID";
            SelectionModeDropDownList.DataBind();
            TranslateListControl(SelectionModeDropDownList);
        }

        /// <summary>
        /// Set the forms to match DB question options
        /// </summary>
        private void BindQuestionOptions()
        {
            // Retrieve the original question values
            QuestionData question = new Questions().GetQuestionById(_questionId);
            QuestionData.QuestionsRow questionRow = question.Questions[0];

            // Assign them to the form
            QuestionFreeTextBox.Text = questionRow.QuestionText;
            DisplayModeDropDownList.SelectedValue =
                (questionRow.IsLayoutModeIdNull()) ? ((int)QuestionLayoutMode.Horizontal).ToString() : questionRow.LayoutModeId.ToString();
            ColumnDropdownlist.SelectedValue = questionRow.ColumnsNumber.ToString();
            SelectionModeDropDownList.SelectedValue = questionRow.SelectionModeId.ToString();
            MinSelectionDropDownList.SelectedValue =
                (questionRow.IsMinSelectionRequiredNull()) ? "0" : questionRow.MinSelectionRequired.ToString();
            MaxAllowedDropDownList.SelectedValue =
                (questionRow.IsMaxSelectionAllowedNull()) ? "0" : questionRow.MaxSelectionAllowed.ToString();

            RandomizeCheckBox.Checked = questionRow.RandomizeAnswers;
            RatingCheckbox.Checked = questionRow.RatingEnabled;
            PipeAliasTextBox.Text = questionRow.QuestionPipeAlias;
            RandomizeCheckBox.Enabled = !RatingCheckbox.Checked;
            ViewState["LibraryId"] = questionRow.IsLibraryIdNull() ? -1 : questionRow.LibraryId;
            if (!questionRow.IsLibraryIdNull() && !NSurveyUser.Identity.IsAdmin)
            {
                CheckRight(NSurveyRights.ManageLibrary, true);
            }

            // Can the question have answers
            if (((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.Answerable) > 0)
            {
                AnswerOptionsPlaceholder.Visible = true;
                EditAnswersButton.Enabled = true;
                MultipleSelection = ((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.MultipleAnswers) > 0;
            }
            else
            {
                AnswerOptionsPlaceholder.Visible = false;
                EditAnswersButton.Enabled = false;
            }
        }

 


        protected void UpdateQuestionButton_Click(object sender, System.EventArgs e)
        {
            if (QuestionFreeTextBox.Text.Length == 0)
            {
                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("MissingQuestionMessage");

            }
            else
            {
                // creates a BE and update the question
                QuestionData question = new QuestionData();
                QuestionData.QuestionsRow updatedQuestion =
                    question.Questions.NewQuestionsRow();

                // Set the updated fields
                updatedQuestion.QuestionId = _questionId;
                updatedQuestion.SurveyId = SurveyId;
                updatedQuestion.QuestionText = QuestionFreeTextBox.Text.Length > 3900 ?
                    QuestionFreeTextBox.Text.Substring(0, 3900) : QuestionFreeTextBox.Text;
                updatedQuestion.ColumnsNumber = int.Parse(ColumnDropdownlist.SelectedValue);
                updatedQuestion.MinSelectionRequired = int.Parse(MinSelectionDropDownList.SelectedValue);
                updatedQuestion.MaxSelectionAllowed = int.Parse(MaxAllowedDropDownList.SelectedValue);
                updatedQuestion.LayoutModeId = int.Parse(DisplayModeDropDownList.SelectedValue);
                updatedQuestion.SelectionModeId = int.Parse(SelectionModeDropDownList.SelectedValue);
                updatedQuestion.RandomizeAnswers = RatingCheckbox.Checked ? false : RandomizeCheckBox.Checked;
                updatedQuestion.RatingEnabled = RatingCheckbox.Checked;
                updatedQuestion.QuestionPipeAlias = PipeAliasTextBox.Text;
                question.Questions.AddQuestionsRow(updatedQuestion);

                new Question().UpdateQuestion(question);

                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("OptionsUpdatedMessage");

                BindQuestionOptions();
            }
        }

        protected void RatingCheckbox_CheckedChanged(object sender, System.EventArgs e)
        {
            // Disable random order option
            // if the rating choice has been checked
            RandomizeCheckBox.Enabled = !RatingCheckbox.Checked;
        }

        protected void ExportXMLButton_Click(object sender, System.EventArgs e)
        {
            Response.Charset = "utf-8";
            Response.ContentType = "application/octet-stream";

            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_question" + _questionId + ".xml\"");

            NSurveyQuestion questionForm = new Questions().GetQuestionForExport(_questionId);
            questionForm.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);
            Response.End();
        }

        int _questionId;

        protected void EditAnswersButton_Click(object sender, System.EventArgs e)
        {
            UINavigator.NavigateToSingleQuestionAnswersEdit(SurveyId, _questionId, (int)ViewState["LibraryId"], MenuIndex);
        }



    }

}
